package com.gzlz.budejie;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import name.fuhan.shipin.ShiPinView;
import name.fuhan.tupian_fh.MyImageView;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.gzlz.budejie.bean.JItemData.TieZi;
import com.gzlz.budejie.bean.JItemData.TieZi.ZuiRe;
import com.gzlz.budejie.bean.JPingLunBean;
import com.gzlz.budejie.bean.JPingLunBean.PingLun;
import com.gzlz.budejie.utils.SP;
import com.gzlz.budejie.view.VoiceView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class PingLunActivity extends Activity implements OnClickListener {

	String 评论列表URL;
	private JPingLunBean pingLunBean; 
	
	TextView pinglun_fanhui;//左上角的返回
	TextView pinglun_diandiandian;//右上角的点点点
	LinearLayout pinglun_tiezi_ll;//帖子内容
	TextView pinglun_remen_tv;//热门评论那几个字
	LinearLayout pinglun_remen_ll;//热门评论区
	ListView pinglun_remen_list;//热门评论的listView
	LinearLayout pinglun_zuixin_ll;//最新评论区
	ListView pinglun_zuixin_list;//最新评论的listView
	private TieZi tieZi;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ping_lun);
		pinglun_fanhui = (TextView) findViewById(R.id.pinglun_fanhui);
		pinglun_diandiandian = (TextView) findViewById(R.id.pinglun_diandiandian);
		pinglun_tiezi_ll = (LinearLayout) findViewById(R.id.pinglun_tiezi_ll);
		pinglun_remen_tv = (TextView) findViewById(R.id.pnglun_remen_tv);
		pinglun_remen_ll = (LinearLayout) findViewById(R.id.pnglun_remen_ll);
		pinglun_remen_list = (ListView) findViewById(R.id.pnglun_remen_list);
		pinglun_zuixin_ll = (LinearLayout) findViewById(R.id.pnglun_zuixin_ll);
		pinglun_zuixin_list = (ListView) findViewById(R.id.pnglun_zuixin_list);
		
		pinglun_fanhui.setOnClickListener(this);
		pinglun_diandiandian.setOnClickListener(this);
		
		
		Intent intent = getIntent();
		tieZi = (TieZi) intent.getSerializableExtra("tiezi");
		
		Log.e("TGAPL", "收到的贴息信息"+tieZi);
		
		View tieziView = 加载帖子的数据();
		pinglun_tiezi_ll.addView(tieziView);//加入肯德基豪华午餐
		
		
		拉取评论内容的网络数据();
		
		
	}


	private void 拉取评论内容的网络数据() {
		String tieziID = tieZi.id;
		String userID = tieZi.user_id;
		评论列表URL = "http://api.budejie.com/api/api_open.php?c=comment&a=dataList&hot=1&data_id="+tieziID+"&userID="+userID;
		//http://api.budejie.com/api/api_open.php?c=comment&a=dataList&data_id=15108138&userID=8919260
		
		new HttpUtils().send(HttpMethod.GET, 评论列表URL, new RequestCallBack<String>() {
			@Override
			public void onFailure(HttpException arg0, String arg1) {
				Toast.makeText(PingLunActivity.this, "网络异常", 0).show();
			}
			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				String json = arg0.result;
				pingLunBean = new Gson().fromJson(json, JPingLunBean.class);
				加载评论内容的数据();
				
			}
		});
	}


	private View 加载帖子的数据() {
		View tieziView;
		switch (Integer.parseInt(tieZi.type)) {
		case 10://  10图片，41视频,29段子,31声音
			tieziView = View.inflate(this, R.layout.liebiao_item_tupian, null);
			MyImageView myImageView = (MyImageView) tieziView.findViewById(R.id.liebiao_item_imageview);
			String is_gif = tieZi.is_gif;
			String address ;
			String address2;
			if("1".equals(is_gif)){
				address = tieZi.gifFistFrame;
			}else {
				address = tieZi.image0;
			}
			address2 = tieZi.image1;
			if (address==null) {
				throw new RuntimeException("#PingLunActivity 地址出现null,"+tieZi);
			}
			myImageView.setAddress(address, address2,"1".equals( is_gif),tieZi.width,tieZi.height);
			break;
		case 41:
			tieziView = View.inflate(this, R.layout.liebiao_item_shipin, null);
			ShiPinView shiPinView = (ShiPinView) tieziView.findViewById(R.id.liebiao_item_shipinview);
			String videoAddress = tieZi.videouri;
			String imgAdress = tieZi.cdn_img;
			int height = Integer.parseInt(tieZi.height);
			int width = Integer.parseInt(tieZi.width);
			shiPinView.setAddress(imgAdress, videoAddress, null, width, height,-1);
			break;
		case 29:
			tieziView = View.inflate(this, R.layout.liebiao_item, null);
			break;
		case 31:
			tieziView = View.inflate(this, R.layout.liebiao_item_shengyin, null);
			VoiceView shengyinView = (VoiceView) tieziView.findViewById(R.id.liebiao_item_shengyinview);
			shengyinView.setAddress(tieZi.voiceuri, tieZi.image0);
			break;
		default:
			throw new RuntimeException("异常异常");
		}
		
		加载公共内容(tieziView);
		
		return tieziView;
		
	}


	private void 加载公共内容(View view) {
		
		//所有类型通用的内容
		 ImageView liebiao_item_icon = (ImageView) view.findViewById(R.id.liebiao_item_icon);//头像
		 TextView liebiao_item_name = (TextView) view.findViewById(R.id.liebiao_item_name);//名字
		 TextView liebiao_item_time = (TextView) view.findViewById(R.id.liebiao_item_time);//时间
		 TextView liebiao_item_text = (TextView) view.findViewById(R.id.liebiao_item_text);//文字内容
//		 liebiao_item_view = (LinearLayout) view.findViewById(R.id.liebiao_item_view);//多媒体内容
		 ImageView liebiao_item_ding_img = (ImageView) view.findViewById(R.id.liebiao_item_ding_img);//点赞
		 TextView liebiao_item_ding_tv = (TextView) view.findViewById(R.id.liebiao_item_ding_tv);//点赞数
		 ImageView liebiao_item_cai_img = (ImageView) view.findViewById(R.id.liebiao_item_cai_img);//踩
		 TextView liebiao_item_cai_tv = (TextView) view.findViewById(R.id.liebiao_item_cai_tv);//踩数
		 ImageView liebiao_item_zhuanfa_img = (ImageView) view.findViewById(R.id.liebiao_item_zhuanfa_img);//转发
		 TextView liebiao_item_zhuanfa_tv = (TextView) view.findViewById(R.id.liebiao_item_zhuanfa_tv);//转发数
		 ImageView liebiao_item_pinglun_img = (ImageView) view.findViewById(R.id.liebiao_item_pinglun_img);//评论
		 TextView liebiao_item_pinglun_tv = (TextView) view.findViewById(R.id.liebiao_item_pinglun_tv);//评论数
		 LinearLayout liebiao_item_zuire_ll = (LinearLayout) view.findViewById(R.id.liebiao_item_zuire_ll);//最热评论区域
		 TextView liebiao_item_zuire_text = (TextView) view.findViewById(R.id.liebiao_item_zuire_text);//最热评论内容
		
		
		//为头像添加点击事件
		 liebiao_item_name.setOnClickListener(userOnClickListener);
		 liebiao_item_icon.setOnClickListener(userOnClickListener);
		
		
		//为点赞添加点击事件
		 liebiao_item_ding_img.setOnClickListener(on点赞Listener);
		 liebiao_item_ding_tv.setOnClickListener(on点赞Listener);
		
		//为踩添加点击事件
		 liebiao_item_cai_img.setOnClickListener(on踩Listener);
		 liebiao_item_cai_tv.setOnClickListener(on踩Listener);
		
		//为转发,分享添加单击事件
		 liebiao_item_zhuanfa_img.setOnClickListener(on转发Listener);
		 liebiao_item_zhuanfa_tv.setOnClickListener(on转发Listener);
		
		

		liebiao_item_ding_tv.setText(tieZi.love);//顶
		
		liebiao_item_cai_tv.setText(tieZi.hate);//踩
		
		liebiao_item_zhuanfa_tv.setText(tieZi.repost);//转发
		
		liebiao_item_pinglun_tv.setText(tieZi.comment);//评论数
		
		liebiao_item_name.setText("id:"+tieZi.screen_name);//名字
		
		liebiao_item_text.setText(tieZi.text);//正文内容
		
		liebiao_item_time.setText(tieZi.created_at);//发布时间
		
		
		//头像名字点击事件
		liebiao_item_name.setTag(tieZi.user_id);
		liebiao_item_icon.setTag(tieZi.user_id);
		
		String 顶踩帖子 = SP.getString(SP.顶踩帖子+tieZi.id);
		liebiao_item_ding_img.setSelected(SP.顶.equals(顶踩帖子));
		liebiao_item_cai_img.setSelected(SP.踩.equals(顶踩帖子));
		
		//顶
		liebiao_item_ding_img.setTag(tieZi);
		liebiao_item_ding_tv.setTag(tieZi);
		
		//踩
		liebiao_item_cai_img.setTag(tieZi);
		liebiao_item_cai_tv.setTag(tieZi);

		//转发,分享
		liebiao_item_zhuanfa_img.setTag(tieZi);
		liebiao_item_zhuanfa_tv.setTag(tieZi);
		
		//评论
		liebiao_item_pinglun_img.setTag(tieZi);
		liebiao_item_pinglun_tv.setTag(tieZi);
		
		
		
		//读取最热评论
		ArrayList<ZuiRe> top_cmt = tieZi.top_cmt;
		if (top_cmt==null||top_cmt.size()==0) {//如果没有最热评论,隐藏
			 liebiao_item_zuire_ll.setVisibility(View.GONE);
		}else {
			 liebiao_item_zuire_ll.setVisibility(View.VISIBLE);
			ZuiRe zuiRe = top_cmt.get(0);
			 liebiao_item_zuire_text.setText(zuiRe.user.username+"："+zuiRe.content);
		}
		
		
		
		
		
//		holder.liebiao_view.setImageBitmap(让精彩填满生活);
		if(!TextUtils.isEmpty(tieZi.profile_image)) {//设置头像
			BitmapUtils bitmapUtils = new BitmapUtils(this);
			BitmapDisplayConfig  bigPicDisplayConfig = new BitmapDisplayConfig();
			bigPicDisplayConfig.setBitmapConfig(Bitmap.Config.RGB_565);
			bitmapUtils.display(liebiao_item_icon, tieZi.profile_image,bigPicDisplayConfig);
		}

		
				
	}

	
	private userOnClickListener userOnClickListener = new userOnClickListener();
	/**
	 * 头像和名字被点击时的监听
	 * 
	 * @author FuHan
	 *
	 */
	public class userOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			String userId = (String) v.getTag();
			Toast.makeText(PingLunActivity.this, userId , 0).show();
		}

	}

	boolean 正在发送中;
	private OnClickListener on点赞Listener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			final TieZi tiezi = (TieZi) v.getTag();
			final LinearLayout dingParent = (LinearLayout) v.getParent();
			final ImageView dingIV = (ImageView) dingParent.getChildAt(0);
			final TextView dingTV = (TextView) dingParent.getChildAt(1);
			LinearLayout parent = (LinearLayout) dingParent.getParent();
			LinearLayout caiParent = (LinearLayout) parent.getChildAt(2);
			ImageView caiIV = (ImageView) caiParent.getChildAt(0);
			
			if (!正在发送中&&!dingIV.isSelected()&&!caiIV.isSelected()) {//没点赞,也没踩,
				正在发送中 = true;
				new HttpUtils().send(HttpMethod.GET, "http://api.budejie.com/api/api_open.php?c=post&a=love&id="+tiezi.id, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						正在发送中 = false;
						Toast.makeText(PingLunActivity.this, "网络请求失败,无法点赞!", 0).show();
					}

					@Override
					public void onSuccess(final ResponseInfo<String> arg0) {
						正在发送中 = false;
						if (arg0.result.equals("0")) {
							Toast.makeText(PingLunActivity.this, "请求失败!", 0).show();
							return;
						}
						SP.putString(SP.顶踩帖子+tiezi.id, SP.顶);
						
						dingIV.setSelected(true);
						dingTV.setTextColor(Color.RED);
						dingTV.setText("+1");
						AlphaAnimation animation = new AlphaAnimation(0, 1);
						animation.setDuration(200);
						AlphaAnimation animation3 = new AlphaAnimation(1, 0);
						animation3.setStartOffset(200);
						animation3.setDuration(300);
						ScaleAnimation animation2 = new ScaleAnimation(0.2f, 1, 0.2f, 1);
						animation2.setDuration(400);
						AnimationSet animationSet = new AnimationSet(false);
						animationSet.addAnimation(animation);
						animationSet.addAnimation(animation3);
						animationSet.addAnimation(animation2);
						animationSet.setAnimationListener(new AnimationListener() {
							@Override
							public void onAnimationStart(Animation animation) {}
							@Override
							public void onAnimationRepeat(Animation animation) {}
							@Override
							public void onAnimationEnd(Animation animation) {
								dingTV.setText(arg0.result);
							}
						});
						dingTV.startAnimation(animationSet);
					}
				});
			}
		}
	};
	private OnClickListener on踩Listener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			final TieZi tiezi = (TieZi) v.getTag();
			final LinearLayout caiParent = (LinearLayout) v.getParent();
			final ImageView caiIV = (ImageView) caiParent.getChildAt(0);
			final TextView caiTV = (TextView) caiParent.getChildAt(1);
			LinearLayout parent = (LinearLayout) caiParent.getParent();
			LinearLayout dingParent = (LinearLayout) parent.getChildAt(0);
			ImageView dingIV = (ImageView) dingParent.getChildAt(0);
			
			if (!正在发送中&&!caiIV.isSelected()&&!dingIV.isSelected()) {//没点赞,也没踩,
				正在发送中 = true;
				new HttpUtils().send(HttpMethod.GET, "http://api.budejie.com/api/api_open.php?c=post&a=cai&id="+tiezi.id, new RequestCallBack<String>() {


					@Override
					public void onFailure(HttpException arg0, String arg1) {
						正在发送中 = false;
						Toast.makeText(PingLunActivity.this, "网络请求失败,无法点赞!", 0).show();
					}

					@Override
					public void onSuccess(final ResponseInfo<String> arg0) {
						正在发送中 = false;
						if (arg0.result.equals("0")) {
							Toast.makeText(PingLunActivity.this, "请求失败!", 0).show();
							return;
						}
						SP.putString(SP.顶踩帖子+tiezi.id, SP.踩);
						caiIV.setSelected(true);
						caiTV.setTextColor(Color.RED);
						caiTV.setText("+1");
						AlphaAnimation animation = new AlphaAnimation(0, 1);
						animation.setDuration(200);
						AlphaAnimation animation3 = new AlphaAnimation(1, 0);
						animation3.setStartOffset(200);
						animation3.setDuration(300);
						ScaleAnimation animation2 = new ScaleAnimation(0.2f, 1, 0.2f, 1);
						animation2.setDuration(400);
						AnimationSet animationSet = new AnimationSet(false);
						animationSet.addAnimation(animation);
						animationSet.addAnimation(animation3);
						animationSet.addAnimation(animation2);
						animationSet.setAnimationListener(new AnimationListener() {
							@Override
							public void onAnimationStart(Animation animation) {}
							@Override
							public void onAnimationRepeat(Animation animation) {}
							@Override
							public void onAnimationEnd(Animation animation) {
								caiTV.setText(arg0.result);
							}
						});
						caiTV.startAnimation(animationSet);
					}
				});
			}
		}
	};
	
	
	private OnClickListener on转发Listener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO 待完成
			TieZi tiezi = (TieZi) v.getTag();
			
		}
	};
	
	
	
	

	protected void 加载评论内容的数据() {
		//加载最热部分
		
		if(pingLunBean.hot==null||pingLunBean.hot.size()==0){//如果没有最热部分
			pinglun_remen_list.setVisibility(View.GONE);
			pinglun_remen_tv.setVisibility(View.GONE);
			pinglun_remen_ll.setVisibility(View.GONE);
		}else {
			pinglun_remen_list.setVisibility(View.VISIBLE);
			pinglun_remen_tv.setVisibility(View.VISIBLE);
			pinglun_remen_ll.setVisibility(View.VISIBLE);
			ArrayList<PingLun> remenData = pingLunBean.hot;
			MyAdatper myAdatper = new MyAdatper(remenData);
			pinglun_remen_list.setAdapter(myAdatper);
			setListViewHeight(pinglun_remen_list);
		}
		
		//加载最新部分
		List<PingLun> zuixinData = pingLunBean.data;
		MyAdatper myAdatper = new MyAdatper(zuixinData);
		pinglun_zuixin_list.setAdapter(myAdatper);
		setListViewHeight(pinglun_zuixin_list);
		
	}

	class MyAdatper extends BaseAdapter{
		//TODO 待完成
		
		BitmapUtils bitmapUtils = new BitmapUtils(PingLunActivity.this);
		
		class ViewHolder {
			ImageView pinglun_item_icon;//头像
			ImageView pinglun_item_sex;//性别
			TextView pinglun_item_name;//名字
			TextView pinglun_item_content;//内容
			ImageView pinglun_item_ding_iv;//顶
			TextView pinglun_item_ding_tv;//顶数
		}
		
		List<PingLun> data;
		public MyAdatper(List<PingLun> data){
			this.data = data;
		}
		
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Log.e("TGAPL", "正在拉取第"+position+"个Item");
			ViewHolder holder;
			if (convertView==null) {
				holder = new ViewHolder();
				convertView = View.inflate(PingLunActivity.this, R.layout.activity_pinglun_item, null);
				holder.pinglun_item_icon = (ImageView) convertView.findViewById(R.id.pinglun_item_icon);
				holder.pinglun_item_sex = (ImageView) convertView.findViewById(R.id.pinglun_item_sex);
				holder.pinglun_item_name = (TextView) convertView.findViewById(R.id.pinglun_item_name);
				holder.pinglun_item_content = (TextView) convertView.findViewById(R.id.pinglun_item_content);
				holder.pinglun_item_ding_iv = (ImageView) convertView.findViewById(R.id.pinglun_item_ding_iv);
				holder.pinglun_item_ding_tv = (TextView) convertView.findViewById(R.id.pinglun_item_ding_tv);
				convertView.setTag(holder);
			}else {
				holder = (ViewHolder) convertView.getTag();
			}
			PingLun pingLun = data.get(position);
			//头像
			if (TextUtils.isEmpty(pingLun.user.profile_image)) {
				holder.pinglun_item_icon.setImageResource(R.drawable.ic_launcher);
			}else {
				bitmapUtils.display(holder.pinglun_item_icon, pingLun.user.profile_image);
			}
			
			if (pingLun.user.sex.equals("f")) {//女的
				holder.pinglun_item_sex.setSelected(true);
			}else {
				holder.pinglun_item_sex.setSelected(false);
			}
			
			holder.pinglun_item_name.setText(pingLun.user.username);//名字
			
			holder.pinglun_item_content.setText(pingLun.content);//内容
			
			String dingPinglunURL = "http://api.budejie.com/api/api_open.php?c=comment&a=like&cid="+pingLun.id+"&userID="+pingLun.user.id;
			String dinglemei = SP.getString(SP.顶评论+pingLun.id);
			if (TextUtils.isEmpty(dinglemei)) {
				//没
				holder.pinglun_item_ding_iv.setSelected(false);
			}else {
				//顶过了
				holder.pinglun_item_ding_iv.setSelected(true);
			}
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("url", dingPinglunURL);
			map.put("cid", pingLun.id);
			holder.pinglun_item_ding_iv.setTag(map);
			holder.pinglun_item_ding_iv.setOnClickListener(on顶评论Listener);
			holder.pinglun_item_ding_tv.setTag(map);
			holder.pinglun_item_ding_tv.setOnClickListener(on顶评论Listener);
			
			
			
			return convertView;
		}
		
		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}
		
	}
	
	OnClickListener on顶评论Listener = new OnClickListener() {
		
		@Override
		public void onClick(final View v) {
			Map<String, String> map = (HashMap<String, String>) v.getTag();
			String url = map.get("url");
			final String cid = map.get("cid");
			
			HttpUtils httpUtils = new HttpUtils();
			httpUtils.send(HttpMethod.GET, url, new RequestCallBack<String>() {

				@Override
				public void onFailure(HttpException arg0, String arg1) {
					Toast.makeText(PingLunActivity.this, "连不上网", 0).show();
				}

				@Override
				public void onSuccess(ResponseInfo<String> arg0) {
					if (arg0.result.equals("1")) {
						//成功了
						ViewGroup parent = (ViewGroup) v.getParent();
						SP.putString(SP.顶评论+cid,"ding");
						parent.getChildAt(0).setSelected(true);
						TextView text = (TextView) parent.getChildAt(1);
						text.setText(Integer.parseInt(text.getText().toString())+1+"");
					}
				}
			});
			
			
		}
	};
	

	@Override
	public void onClick(View v) {
		if (v==pinglun_fanhui) {
			finish();
		}
		if (v==pinglun_diandiandian) {
			//TODO 分享
			Toast.makeText(this, "分享", 0).show();
		}
		
	}

	
	/**  
     * 重新计算ListView的高度，解决ScrollView和ListView两个View都有滚动的效果，在嵌套使用时起冲突的问题  
     * @param listView  
     */  
    public void setListViewHeight(ListView listView) {    
            
        // 获取ListView对应的Adapter    
        
        BaseAdapter listAdapter = (BaseAdapter) listView.getAdapter();    
        
        if (listAdapter == null) {    
            return;    
        }    
        int totalHeight = 0;    
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目    
            View listItem = listAdapter.getView(i, null, listView);    
            listItem.measure(0, 0); // 计算子项View 的宽高    
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度    
        }    
        
        ViewGroup.LayoutParams params = listView.getLayoutParams();    
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));    
        listView.setLayoutParams(params);    
    } 

}
